package cn.stacey.blog.web.demo;

import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import cn.stacey.blog.domain.AjaxResponse;
import cn.stacey.blog.domain.Category;
import cn.stacey.blog.service.CategoryService;

public class BaseServlet extends HttpServlet{
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//写一个post请求来处理doGet
		doGet(req, resp);
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		//category_list->就调用findAll
		//category_insert->就调用insert方法
		
		//1.获取请求路径，截取最后一部分，得到一个方法名
		String uri = req.getRequestURI();		
		int index =uri.lastIndexOf('/');
		String methodName = uri.substring(index+1);
		Method method;
		try {
			//2.根据方法名，调用servlet里面对应的方法
			//??HttpServletRequest.class
			method = getClass().getMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
			method.invoke(this, req,resp);// 相当于this.findAll(req, resp);
		}catch (NoSuchMethodException | IllegalAccessException | SecurityException | IllegalArgumentException | InvocationTargetException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		} 
	
	//将PostServlet中的findAll方法中的相同代码抽取出来，用泛型表示，简化代码
	public <E> void writeListData(HttpServletResponse resp,List<E> data) throws IOException {
		AjaxResponse<E> ajax = new AjaxResponse<>();
		ajax.setCode(0);
		ajax.setMsg("");
		ajax.setData(data);
		String string = JSON.toJSONString(ajax);
		resp.setContentType("application/json;charset=utf-8");
		resp.getWriter().write(string);
	}
	
	public <E> void writePageData(HttpServletResponse resp, AjaxResponse<E> result) throws IOException {
		String string = JSON.toJSONString(result);
		resp.setContentType("application/json;charset=utf-8");
		resp.getWriter().write(string);
	}

}
